<?php

namespace App\Http\Controllers;

use App\Http\Requests\GlobalRequest;
use App\Models\ChatUsers;
use App\Models\FilesModel;
use App\Services\GlobalService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Symfony\Component\HttpFoundation\File\Stream;

class GlobalController extends BaseController
{

    public function __construct(GlobalService $services, GlobalRequest $request)
    {
        parent::__construct();

        $this->services = $services;
        $this->request = $request;
    }

    /**
     * Reference数据
     */
    public function reference()
    {
        return $this->success($this->services->reference());
    }
    /**
     * 文件上传
     * @param stream $file *文件流
     * @param string $type *类型：文件file，图片img，视频video，多媒体编辑器editor
     */
    public function upload(Request $request): JsonResponse
    {
        set_time_limit(3600);
        $rules = [
            'file' => 'required|file',
        ];
        $this->validate($request, $rules);
        $file = $request->file('file');
        $name = $file->getClientOriginalName();
        $type = pathinfo($name,PATHINFO_EXTENSION);
        $size = $file->getSize();
        $extension = $file->getClientOriginalExtension();
        $filename = date('YmdHis') . uniqid() . '.' . $extension;
        $path = $file->storeAs( $type, $filename);
        $url = Storage::url($path);
        // 生成缩略图
        $thumbnail_filename = date('YmdHis') . uniqid() . '_100x100' . '.' . $extension;
        $thumbnailPath = $file->storeAs('thumbnail/' . $type, $thumbnail_filename);
        $thumbnail = Image::make($file)->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        });
        // 获取缩略图的 URL
        $thumbnail_url = Storage::url($thumbnailPath);
        Storage::put($thumbnailPath, (string) $thumbnail->encode());

        $file = FilesModel::create(compact('type', 'path', 'url', 'name', 'size', 'thumbnail_url'));

        $uploadType = $request->input('uploadType');
        //如果用户id 不为空 则添加图片为用户头像
        $chat_user_id = $request->input('user_id');
        if (!empty($chat_user_id) && empty($uploadType)){
            ChatUsers::where('id',$chat_user_id)->update([
                'avatar' =>  $url,
                'mini_avatar' =>  $thumbnail_url
            ]);
        }
        // 类型 chat_bg_img为聊天背景图，picture_banner朋友圈背景图
        if ($uploadType  && $chat_user_id){
            ChatUsers::where('id',$chat_user_id)->update([
                $uploadType =>  $url,
            ]);
        }

        if ($type == 'editor') {
            return response()->json([
                'errno' => '0',
                'data' => [
                    [
                        'url' => $file->url,
                        'alt' => $file->name,
                        'href' => ''
                    ]
                ]
            ]);
        } else {
            return $this->success(['id' => $file->id, 'name' => $file->name, 'url' => url($url), 'path' => $file->path, 'type' => $file->type, 'thumbnail_url' => url($thumbnail_url)]);
        }
    }
}
